package com.xh.shuati.controller;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xh.shuati.annotation.RateLimiter;
import com.xh.shuati.common.BaseResponse;
import com.xh.shuati.common.DeleteRequest;
import com.xh.shuati.common.ErrorCode;
import com.xh.shuati.common.ResultUtils;
import com.xh.shuati.constant.UserConstant;
import com.xh.shuati.exception.BusinessException;
import com.xh.shuati.exception.ThrowUtils;
import com.xh.shuati.model.dto.question.*;
import com.xh.shuati.model.entity.Question;
import com.xh.shuati.model.entity.User;
import com.xh.shuati.model.enums.LimitTypeEnum;
import com.xh.shuati.model.vo.QuestionVO;
import com.xh.shuati.service.QuestionService;
import com.xh.shuati.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.redisson.api.RateIntervalUnit;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

import static com.xh.shuati.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 题目接口
 *
 * @author <a href="https://github.com/canon0521">xh</a>
 */
@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;


    // region 增删改查

    /**
     * 创建题目
     *
     * @param questionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(questionAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();

        List<String> tags = questionAddRequest.getTags();
        if (tags != null) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }
        BeanUtils.copyProperties(questionAddRequest, question);
        // 数据校验
        questionService.validQuestion(question, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        question.setUserId(loginUser.getId());
        question.setCloseChangeId(loginUser.getId());
        // 写入数据库
        boolean result = questionService.save(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newQuestionId = question.getId();
        return ResultUtils.success(newQuestionId);
    }

    /**
     * 删除题目
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null || request == null, ErrorCode.PARAMS_ERROR,"参数不能为空");
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null || oldQuestion.getUserId() == null, ErrorCode.PARAMS_ERROR,"题目不存在");
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }

        // 操作数据库
        oldQuestion.setIsDelete(1);
        oldQuestion.setEditTime(new Date());
        oldQuestion.setCloseChangeId(id);
        boolean save = questionService.deleteQuestionById(oldQuestion);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR,"删除失败");
        return ResultUtils.success(true);
    }

    /**
     * 更新题目（仅管理员可用）
     *
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        List<String> tags = questionUpdateRequest.getTags();
        if (tags != null) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }
        BeanUtils.copyProperties(questionUpdateRequest, question);
        // 数据校验
        questionService.validQuestion(question, false);
        // 判断是否存在
        long id = questionUpdateRequest.getId();
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND);
        Object userObj = StpUtil.getSession().get(USER_LOGIN_STATE);
        User loginUser = (User) userObj;
        question.setCloseChangeId(loginUser.getId());
        // 操作数据库
        boolean result = questionService.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取题目（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    @RateLimiter(key = "getQuestionVOById", CountTime = 10, LimitCount = 20, timeUnit = RateIntervalUnit.SECONDS, limitType = LimitTypeEnum.REJECT_USER)
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Question question = questionService.getQuestionById(id);
        ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND);
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVO(question));
    }



    //检测爬虫
//    @Resource
//    private CounterManager counterManager;
//
//    private void crawlCheck(long loginUserId) {
//        //警告阈值
//        final int WARN_COUNT = 10;
//        //封号阈值
//        final int BAN_COUNT = 20;
//
//        String key = String.format("user:access:%s",loginUserId);
//
//        long count = counterManager.incrAndGetCounter(key);
//
//        if (count > BAN_COUNT) {
//            //踢下线
//            StpUtil.kickout(loginUserId);
//            User  banUser = new User();
//            banUser.setId(loginUserId);
//            banUser.setUserRole(UserConstant.BAN_ROLE);
//            userService.updateById(banUser);
//            throw  new BusinessException(ErrorCode.NO_AUTH,  "访问次数过多，您已被封号");
//        }
//        if (count == WARN_COUNT) {
//            //警告
//            throw  new BusinessException(110,  "警告！访问太频繁");
//        }
//
//    }

    /**
     * 分页获取题目列表（仅管理员可用）
     *
     * @param questionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest) {
        ThrowUtils.throwIf(questionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.listQuestionByPage(questionQueryRequest);
        return ResultUtils.success(questionPage);
    }


    /**
     * 分页获取题目列表（限流实现）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo/sentinel")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPageBySentinel(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 300, ErrorCode.PARAMS_ERROR);

        //基于ip限流
        String ip = request.getRemoteAddr();
        Entry entry = null;
        try {
            entry = SphU.entry("listQuestionVOByPage", EntryType.IN, 1, ip);
            // 查询数据库
            Page<Question> questionPage = questionService.page(new Page<>(current, size),
                    questionService.getQueryWrapper(questionQueryRequest));
            // 获取封装类
            return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
        } catch (Throwable ex) {
            if(!BlockException.isBlockException(ex)){
                Tracer.trace(ex);
                return  ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
            }
            //如果是降级操作
            if (ex instanceof DegradeException) {
                return handleFallback(questionQueryRequest,request,ex);
            }
            // 限流操作
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "访问过于频繁，请耐心等待");
        } finally {
            if (entry != null) {
                entry.exit(1, ip);//传什么释放什么
            }
        }
    }

    public BaseResponse<Page<QuestionVO>> handleFallback(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                             HttpServletRequest request, Throwable ex) {
        // 可以返回本地数据或空数据
        return ResultUtils.success(null);
    }


    /**
     * 分页获取题目列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    @RateLimiter(key = "listQuestionVOByPage", CountTime = 10, LimitCount = 20, timeUnit = RateIntervalUnit.SECONDS, limitType = LimitTypeEnum.REJECT_USER)
    @SentinelResource(
            value = "listQuestionVOByPage",
            entryType = EntryType.IN, // 表示这是一个外部请求入口
            blockHandler = "handleBlockException",
            fallback = "handleFallback")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 300, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 限流策略
     * @param questionQueryRequest
     * @param e
     * @return
     */
    public BaseResponse<Page<QuestionVO>> handleBlockException(QuestionQueryRequest questionQueryRequest, HttpServletRequest request,
                                                               BlockException e) {
        return ResultUtils.error(ErrorCode.NOT_VISIT, "访问过于频繁，请稍后再试");
    }

    /**
     * 降级策略
     */
    public BaseResponse<Page<QuestionVO>> handleFallback(QuestionQueryRequest questionQueryRequest, HttpServletRequest request
            ,DegradeException e){
        // 可以返回本地数据或空数据
        try {
            Page<QuestionVO> questionFromCache = questionService.getQuestionFromCache(questionQueryRequest);
            if(ObjectUtils.isNotEmpty(questionFromCache)){
                return ResultUtils.success(questionFromCache);
            }
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "系统繁忙,请稍后再试");
        } catch (Exception ex) {
            log.error("从缓存获取问题列表失败", ex);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统服务降级中，请稍后再试");
        }
    }


    /**
     * 分页获取当前登录用户创建的题目列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
//    @RateLimiter(key = "listMyQuestionVOByPage", CountTime = 10, LimitCount = 20, timeUnit = RateIntervalUnit.SECONDS, limitType = LimitTypeEnum.REJECT_USER)
    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(questionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 编辑题目（给用户使用）
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @RateLimiter(key = "editQuestion", CountTime = 10, LimitCount = 20, timeUnit = RateIntervalUnit.SECONDS, limitType = LimitTypeEnum.REJECT_USER)
    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);
        List<String> tags = questionEditRequest.getTags();
        if (tags != null) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }
        // 数据校验
        questionService.validQuestion(question, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = questionEditRequest.getId();
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        question.setCloseChangeId(loginUser.getId());
        // 操作数据库
        boolean result = questionService.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取题目列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/search/page/vo")
    @RateLimiter(key = "searchQuestionVOByPage", CountTime = 10, LimitCount = 20, timeUnit = RateIntervalUnit.SECONDS, limitType = LimitTypeEnum.REJECT_USER)
    public BaseResponse<Page<QuestionVO>> searchQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest, HttpServletRequest request) {

        //1.限流开启
        String remoteAddr = request.getRemoteAddr();
        Entry entry = null;
        try {
            entry = SphU.entry("searchQuestionVOByPage", EntryType.IN, 1, remoteAddr);
            //2.查询数据
            //2.1查询 ES
            Page<Question> questionPage = questionService.searchFromEs(questionQueryRequest);
            return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
        }catch (Exception ex){
            if(ex instanceof BlockException){
                //3.1降级方案
                if(ex instanceof DegradeException){
                    //2.2从数据库中获取
                    Page<Question> SQLquestionPage = questionService.listQuestionByPage(questionQueryRequest);
                    return ResultUtils.success(questionService.getQuestionVOPage(SQLquestionPage, request));
                }
                //3.2限流方案
                return ResultUtils.error(ErrorCode.SYSTEM_ERROR,"系统繁忙，请稍后再试");
            }else{
                return ResultUtils.error(ErrorCode.SYSTEM_ERROR,"系统错误");
            }
        }finally {
            if(entry != null){
                entry.exit(1,remoteAddr);
            }
        }
    }


    @PostMapping("/delete/batch")
    public BaseResponse<Boolean> batchdeleQuestion(@RequestBody QuestionBatchDeleRequest questionBatchDeleRequest) {
        ThrowUtils.throwIf(questionBatchDeleRequest == null || questionBatchDeleRequest.getIds() == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(questionBatchDeleRequest.getIds().size()<=0, ErrorCode.PARAMS_ERROR, "请选择要删除的题目");
        questionService.batchDeleQuestions(questionBatchDeleRequest.getIds());
        return ResultUtils.success(true);
    }


    /**
     * AI生成题目接口
     * @param aiGenerateQuestionRequest 请求参数
     * @param request HTTP请求
     * @return 是否成功
     */
    @PostMapping("/ai/generate/question")
    @SaCheckRole(UserConstant.ADMIN_ROLE) // 仅管理员可用
    public BaseResponse<Boolean> aiGenerateQuestions(
            @RequestBody QuestionAiGenerateRequest aiGenerateQuestionRequest,
            HttpServletRequest request) {

        // 参数校验
        if (aiGenerateQuestionRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String questionType = aiGenerateQuestionRequest.getQuestionType();
        Integer number = aiGenerateQuestionRequest.getNumber();

        if (ObjectUtil.hasEmpty(questionType, number)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        if (number <= 0 || number > 100) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "生成数量需在1-100之间");
        }

        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);

        // 调用Service方法
        boolean result = questionService.aiGenerateQuestions(questionType, number, loginUser);

        return ResultUtils.success(result);
    }
    // endregion
}
